﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;


namespace FileDownLoadDemo
{
    public partial class fileDown : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        #region TransmitFile，实现下载
        /// <summary>
        /// TransmitFile，实现下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnTransmitFileDown_Click(object sender, EventArgs e)
        {
            /*
             * 微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite
             * 下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。
             * 代码如下：
             */
            //7z压缩格式
            Response.ContentType = "application/x-7z-compressed";
            Response.AddHeader("Content-Disposition", "attachment;filename=Trunk.7z");
            string filePath = Server.MapPath("DownLoad/Trunk.7z");
            Response.TransmitFile(filePath);
        }
        #endregion

        #region WriteFile方式，实现下载
        /// <summary>
        /// WriteFile方式，实现下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnWriteFile_Click(object sender, EventArgs e)
        {
            string fileName = "sumaryDemo123.txt"; //客户端保存的文件名
            string filePath = Server.MapPath("DownLoad/sumaryDemo.txt"); //文件路径
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
        }
        #endregion

        #region WriteFile分块方式，实现下载

        /// <summary>
        /// WriteFile分块方式，实现下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFileInfo_Click(object sender, EventArgs e)
        {
            string fileName = "你好.txt";
            string filePath = Server.MapPath("Download/sumaryDemo.txt");
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            if (fileInfo.Exists)
            {
                //每次只读取100 * 1024=100kb,减少服务器压力
                const long readSize = 100 * 1024;
                Byte[] buffer = new byte[readSize];
                Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载文件的总共大小
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
                // Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.HtmlEncode(fileName));
                while (dataLengthToRead > 0 && Response.IsClientConnected)
                {
                    //每次读取文件的大小
                    Int32 lengthReadTemp = iStream.Read(buffer, 0, Convert.ToInt32(readSize));
                    Response.OutputStream.Write(buffer, 0, lengthReadTemp);
                    Response.Flush();
                    //计算余下的文件大小
                    dataLengthToRead -= lengthReadTemp;
                }
                Response.Close();
            }
        }
        #endregion

        #region  字符流方式，实现下载

        /// <summary>
        /// 字符流方式，实现下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFileStream_Click(object sender, EventArgs e)
        {
            string fileName = "测试文件下载.txt";
            string filePath = Server.MapPath("Download/sumaryDemo.txt");
            System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate);
            Byte[] buffer = new Byte[(long)fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();

            Response.ContentType = "application/octet-stream";
            //通知浏览器 下载文件，而不是打开文件
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(buffer);
            Response.Flush();
            Response.End();
        }
        #endregion


        protected void Button1_Click(Object sender, EventArgs e)
        {
            string filePath = Server.MapPath("Download/123.xls");
            GridView gv = new GridView();

           

            string fileName = "123.xls";
           
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            //下面这行很重要， attachment 参数表示作为附件下载，您可以改成 online在线打开
            //filename=FileFlow.xls 指定输出文件的名称，注意其扩展名和指定文件类型相符，可以为：.doc 　　 .xls 　　 .txt 　　.htm
            Response.AppendHeader("Content-Disposition", "inline;filename=" + fileName);
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //Response.ContentType指定文件类型 可以为
            //application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;
            //　定义一个输入流
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
             
             gv.RenderControl(oHtmlTextWriter);
          //this.  Table_Report.RenderControl(oHtmlTextWriter);
            //this 表示输出本页，你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
            Response.Write(oStringWriter.ToString());
            Response.End();
        }


    }
}